import { TimeManager } from './../common/timeManager';
import { LocalstorageDataManage } from './../common/localstoreage/localstoreageDataManage';
import { expeditionOrdersRestApi, ExpeditionOrdersRestApi } from './../common/http/rest-api';
import { ExpeditionOrder } from './../models/expeditionOrder';
import { businsessHttpServer } from './../common/http/http-server';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import * as R from 'ramda';
import * as moment from 'moment';
import { Debounce } from "../common/decorator/index";

class ExpeditionOrders {
    orders: Array<ExpeditionOrder>; //应该是一个队列 暂时先忽略对的情况，先不删除
    observable: BehaviorSubject<Array<ExpeditionOrder>> = new BehaviorSubject([]);
    expeditionOrdersRestApi: ExpeditionOrdersRestApi;
    constructor(expeditionOrdersRestApi) {
        this.expeditionOrdersRestApi = expeditionOrdersRestApi;
        this.init();
    }


    getObservableByPredication(predication: (order) => void) {
        return this.getObservable().map((orders = []) => orders.filter(predication));
    }

    notExpeditionOrders$
    getNotExpeditionOrders() {
        if (!this.notExpeditionOrders$)
            this.notExpeditionOrders$ = this.getObservableByPredication(x => x.status == "expedited").share();
        return this.notExpeditionOrders$;
    }

    expeditionOrders$
    getExpeditionOrders() {
        if (!this.expeditionOrders$)
            this.expeditionOrders$ = this.getObservableByPredication(x => x.status == "delivered").share();
        return this.expeditionOrders$;
    }

    async init() {
        const KDSs = LocalstorageDataManage.current.getValidKDSs();
        const start = moment().startOf('day').subtract(0, 'days').valueOf();
        this.orders = (await this.expeditionOrdersRestApi.getOrders({
            query: {
                sourceTerminalIds: KDSs && KDSs.map(x => x.id),
                status: ["expedited", "delivered"],
                start: start
            }
        })).map(order => {
            delete order.items
            return order;
        })
        this.notify()
    }

    @Debounce(300)
    notify() {
        this.observable.next(this.orders);
    }

    getObservable() {
        return this.observable.share();
    }

    async addOrder(order: ExpeditionOrder) {
        delete order.items
        if (!(LocalstorageDataManage.current.getValidKDSs().map(x => x.id).indexOf(order.sourceTerminalId) > -1)) return;
        const exsitOrder = this.orders.find(x => x.id == order.id);
        if (exsitOrder) {
            exsitOrder.status = order.status;
            exsitOrder.deliveryBeginTime = order.deliveryBeginTime;
            exsitOrder.deliveryer = order.deliveryer;
        } else {
            this.orders.push(order);
        }
        this.orders = this.orders.filter(order => order.status == "expedited" || order.status == "delivered")
        this.notify();
    }

    async deliverBatchExpeditionOrder(ids: Array<string>, deliveryer: {
        id: string;
        name: string;
    }) {
        //todo 这里统一格式 知乎上面看到过
        // const result = await this.expeditionOrdersRestApi.deliverBatchExpeditionOrder({ id:"batch", controller: "delivery" }, {ids, deliveryer });
        const result = await this.expeditionOrdersRestApi.deliverBatchExpeditionOrder({ ids, deliveryer });
        // R.merge(this.orders.find(order => order.id == id))(result.currentOrder) //todo 更好的方式
        result.orders.forEach(expOrder => {
            this.orders.find(order => order.id == expOrder.id).deliveryBeginTime = expOrder.deliveryBeginTime;
            this.orders.find(order => order.id == expOrder.id).deliveryer = expOrder.deliveryer;
        })
        this.notify();
        return result;
    }
}


export const expeditionOrdersService = new ExpeditionOrders(expeditionOrdersRestApi);